package demo;

import java.util.concurrent.Semaphore;

public class W7_ZeroEvenOdd {
	private int n;
    private Semaphore zeroSe;
    private Semaphore evenSe;
    private Semaphore oddSe;

    public W7_ZeroEvenOdd(int n) {
        this.n = n;
        this.zeroSe = new Semaphore(1);
        this.evenSe = new Semaphore(0);
        this.oddSe = new Semaphore(0);
    }

    public void zero() throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            zeroSe.acquire();
            System.out.print(0);
            if (i % 2 == 0) {
                evenSe.release();
            } else {
                oddSe.release();
            }
        }
    }

    public void even() throws InterruptedException {
        for (int i = 2; i <= n; i += 2) {
            evenSe.acquire();
            System.out.print(i);
            zeroSe.release();
        }
    }

    public void odd() throws InterruptedException {
        for (int i = 1; i <= n; i += 2) {
            oddSe.acquire();
            System.out.print(i);
            zeroSe.release();
        }
    }
}
